<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from "@/utils/request";
import type { FormItemRule } from 'element-plus';


// 默认查询表单
const getDefaultSearchForm = () => ({
  pageNo: 1,
  pageSize: 10,
  name: "",
  status: '',
  phone: "",
  companyId: null,
});

// 类型定义
type ServiceItem = {
  id: number; // 添加 ID 字段
  companyId: number;
  companyName?: string;
  name: string;
  employeeNo: string;
  phone: string;
  email: string;
  hireDate: string;
  status: number;
  [key: string]: any; // 其他动态属性
};

type Company = {
  value: number;
  label: string;
};

// 状态管理
const searchForm = ref(getDefaultSearchForm());
const list = ref<ServiceItem[]>([]);
const total = ref<number>(0);
const companyList = ref<Company[]>([]);
const selectedIds = ref<number[]>([]); // 批量删除的选中 ID 集合
const fullscreenLoading = ref(false)  //全屏loading

// 获取客服列表
const getList = () => {
    // 开始加载
    fullscreenLoading.value = true;
  request.post('/api/v1/service/searchService', searchForm.value).then(res => {
    const { data } = res;
    list.value = data.list.map(item => {
      const company = companyList.value.find(c => c.value === item.companyId);
      item.companyName = company ? company.label : "未知公司";
      return item;
    });
    total.value = data.total;
    }) .catch(err => {
      console.error("获取客服列表失败:", err);
    })
    .finally(() => {
      // 请求完成，结束加载
      fullscreenLoading.value = false;
    });
};

// 获取公司列表
const getCompanyList = () => {
  request.get('/api/v1/service/company').then(res => {
    companyList.value = res.data;
  });
};

// 初始化数据
getCompanyList();
getList();

// 重置查询
const resetSearch = () => {
  searchForm.value = getDefaultSearchForm();
  getList();
};

// 分页变化
const currentChange = (pageNo: any) => {
  searchForm.value.pageNo = pageNo;
  getList();
};

// 监听表格选中变化
const handleSelectionChange = (selection: ServiceItem[]) => {
  selectedIds.value = selection.map(item => item.id);
};


// 表单验证规则
const addFormRules: Partial<Record<string, FormItemRule[]>> = {
  name: [
    { required: true, message: "客服名称不能为空", trigger: "blur" },
  ],
  companyId: [
    { required: true, message: "请选择公司", trigger: "change" },
  ],
  employeeNo: [
    { required: true, message: "客服编号不能为空", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "手机号码不能为空", trigger: "blur" },
    { type: "string", pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { type: "email", pattern: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/ , message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  hireDate: [
    { required: true, message: "请选择入职日期", trigger: "change" },
  ],
  status: [
    { required: true, message: "请选择状态", trigger: "change" },
  ],
};
// 表单验证规则
const editFormRules: Partial<Record<string, FormItemRule[]>> = {
  name: [
    { required: true, message: "客服名称不能为空", trigger: "blur" },
  ],
  companyId: [
    { required: true, message: "请选择公司", trigger: "change" },
  ],
  phone: [
    { required: true, message: "手机号码不能为空", trigger: "blur" },
    { type: "string", pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { type: "email", pattern: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/, message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  hireDate: [
    { required: true, message: "请选择入职日期", trigger: "change" },
  ],
  status: [
    { required: true, message: "请选择状态", trigger: "change" },
  ],
};

const editFormRef = ref(); // 用于编辑表单的 ref
const addFormRef = ref(); // 用于表单的 ref
// 表单逻辑：新增
const addForm = ref({
  id: null,          // 客服ID
  companyId: "",    // 公司ID
  name: "",          // 客服名称
  employeeNo: "",   // 客服编号
  phone: "",         // 手机号
  email: "",         // 邮箱
  hireDate: "",     // 入职日期
  status: ""         // 状态
});
const dialogVisible = ref(false);
//编辑表单
const editForm  = ref({
  id: null,          // 客服ID
  companyId: "",    // 公司ID
  name: "",          // 客服名称
  phone: "",         // 手机号
  email: "",         // 邮箱
  hireDate: "",     // 入职日期
  status: ""         // 状态
});
const dialogVisible2 = ref(false);

// 打开编辑对话框
const editService = (row: any) => {
  editForm.value = {
    id: row.id || null,
    companyId: row.companyId || "",
    name: row.name || "",
    phone: row.phone || "",
    email: row.email || "",
    hireDate: row.hireDate || "",
    status: row.status
    // status: row.status === 0 ? "启用" : row.status === 1 ? "禁用" : ""
  }; // 填充表单
  dialogVisible2.value = true;
};

// 打开新增对话框
const openAddDialog = () => {
  addForm.value = { id: null, companyId: "", name: "", employeeNo: "", phone: "", email: "", hireDate: "", status: "" };
  dialogVisible.value = true;
};


const handleSubmit = () => {
  // 处理 hireDate 格式
  const processHireDate = (form : any) => {
    if (form.hireDate) {
      try {
        const localDate = new Date(form.hireDate);
        if (!isNaN(localDate.getTime())) {
          localDate.setMinutes(localDate.getMinutes() - localDate.getTimezoneOffset());
          form.hireDate = localDate.toISOString().split('T')[0] + 'T00:00:00';
        } else {
          console.error("Invalid hireDate:", form.hireDate);
          form.hireDate = ""; // 重置为有效的默认值
        }
      } catch (error) {
        console.error("Error processing hireDate:", error);
        form.hireDate = ""; // 重置为有效的默认值
      }
    }
  };
 // if (addForm.value.id)作用是 新增表单的id为空时，不执行
  if (editForm.value.id) {

    // 编辑表单
    processHireDate(editForm.value); // 调整 hireDate 格式
    editFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 编辑表单提交逻辑
      processHireDate(editForm.value); // 调整 hireDate 格式
      request
        .put('/api/v1/service/updateService', editForm.value)
        .then(() => {
          dialogVisible2.value = false; // 关闭编辑对话框
          getList(); // 刷新列表
        })
        .catch((error) => {
          console.error("Error updating service:", error);
        });
    } else {
      ElMessage.warning("请输入正确信息格式");
    }
  });
  } else {
    // 新增表单
    processHireDate(addForm.value); // 调整 hireDate 格式
    addFormRef.value.validate((valid: boolean) => {
    if (valid) {
      request
        .post('/api/v1/service/addService', addForm.value)
        .then(() => {
          dialogVisible.value = false;
          ElMessage.success("新增成功");
          getList(); // 刷新列表
        })
        .catch((error) => {
          console.error("Error adding service:", error);
          ElMessage.error("新增失败，请重试");
        });
    } else {
      ElMessage.warning("请输入正确信息格式");
    }
  });
  }
};



// 删除客服
const deleteService = (id: number) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    request.delete(`/api/v1/service/deleteService/${id}`).then(() => {
      ElMessage.success('删除成功');
      getList();
    }).catch(() => {
      ElMessage.error('删除失败，请重试');
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};


// 定义客服详情类型
interface ServiceDetail {
  name?: string;
  companyName?: string;
  employeeNo?: string;
  phone?: string;
  email?: string;
  hireDate?: string;
  status?: number;
}

// 对话框的可见状态
const dialogVisible3 = ref(false);

// 当前客服详情
const currentService = ref<ServiceDetail>({
  name: "",
  companyName: "",
  employeeNo: "",
  phone: "",
  email: "",
  hireDate: "",
  status: undefined,
});

// 查看客服详情方法
const viewService = (row: ServiceDetail) => {
  currentService.value = { ...row }; // 填充数据
  dialogVisible3.value = true; // 打开对话框
};

// 关闭对话框
const handleClose = () => {
  dialogVisible3.value = false;
  currentService.value = {}; // 清空数据
};

</script>

<template>
  <div style="padding: 16px;">
    <el-card :body-style="{ paddingBottom: '0' }">
      <el-form inline>
        <el-form-item label="客服名称">
          <el-input v-model="searchForm.name" placeholder="请输入客服名称" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入客服手机号" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 200px;">
            <el-option label="启用" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称">
          <el-select v-model="searchForm.companyId" placeholder="请选择公司" style="width: 200px;">
            <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button  v-loading.fullscreen.lock="fullscreenLoading"    @click="getList" type="primary">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 16px;">
      <template #header>
        <el-button @click="openAddDialog" type="primary">新增</el-button>
      </template>
      <el-table
        :data="list"
        @selection-change="handleSelectionChange"
        style="text-align: center;"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="客服名称" width="100" />
        <el-table-column prop="employeeNo" label="客服编号" />
        <el-table-column prop="companyName" label="所在公司" width="200" />

        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="success">启用</el-tag>
            <el-tag v-if="row.status === 1" type="warning">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="200" />
        <el-table-column prop="email" label="邮箱" width="250" />
        <el-table-column prop="hireDate" label="入职日期" width="250" show-overflow-tooltip />
        <el-table-column label="操作" width="300" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="success" @click="viewService(row)">查看</el-button>
            <el-button type="primary" @click="editService(row)">编辑</el-button>
            <el-button type="danger"  @click="deleteService(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="currentChange" :total="total" layout="prev, pager, next" />
    </el-card>
    <el-dialog v-model="dialogVisible" title="新增客服" top="0">
  <el-form
    ref="addFormRef"
    :model="addForm"
    :rules="addFormRules"
    label-position="top"
  >
    <el-form-item label="客服名称" prop="name">
      <el-input v-model="addForm.name" />
    </el-form-item>
    <el-form-item label="客服编号" prop="employeeNo">
      <el-input v-model="addForm.employeeNo" />
    </el-form-item>
    <el-form-item label="公司名称" prop="companyId">
      <el-select v-model="addForm.companyId" placeholder="请选择公司">
        <el-option
          v-for="item in companyList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="addForm.phone" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="addForm.email" />
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-select v-model="addForm.status" placeholder="请选择状态">
        <el-option label="启用" :value="0" />
        <el-option label="禁用" :value="1" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职日期" prop="hireDate">
      <el-date-picker v-model="addForm.hireDate" type="date" placeholder="选择日期" />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="dialogVisible = false">取消</el-button>
    <el-button type="primary" @click="handleSubmit">确定</el-button>
  </template>
</el-dialog>

    
<el-dialog v-model="dialogVisible2" title="编辑客服" top="0">
  <el-form
    ref="editFormRef"
    :model="editForm"
    :rules="editFormRules"
    label-position="top"
  >
    <el-form-item label="客服名称" prop="name">
      <el-input v-model="editForm.name" />
    </el-form-item>
    <el-form-item label="公司名称" prop="companyId">
      <el-select v-model="editForm.companyId" placeholder="请选择公司">
        <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="editForm.phone" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="editForm.email" />
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-select v-model="editForm.status" placeholder="请选择状态">
        <el-option label="启用" :value="0" />
        <el-option label="禁用" :value="1" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职日期" prop="hireDate">
      <el-date-picker v-model="editForm.hireDate" type="date" placeholder="选择日期" />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="dialogVisible2 = false">取消</el-button>
    <el-button type="primary" @click="handleSubmit">确定</el-button>
  </template>
</el-dialog>


     <!-- 查看客服详情对话框 -->
     <el-dialog
      title="客服详情"
      v-model="dialogVisible3"
      width="500px"
      @close="handleClose"
    >
      <el-descriptions border column="1" size="large">
        <el-descriptions-item label="客服名称">{{ currentService.name || "未知" }}</el-descriptions-item>
        <el-descriptions-item label="所在公司">{{ currentService.companyName || "未知公司" }}</el-descriptions-item>
        <el-descriptions-item label="客服编号">{{ currentService.employeeNo || "未设置" }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ currentService.phone || "未设置" }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentService.email || "未设置" }}</el-descriptions-item>
        <el-descriptions-item label="入职日期">{{ currentService.hireDate || "未设置" }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          {{ currentService.status === 0 ? "启用" : "禁用" }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button type="primary" @click="dialogVisible3 = false">关闭</el-button>
      </template>
    </el-dialog>

  </div>
</template>
